/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ericsson.nfc.signing.record;

/**
 *
 * @author emarkki
 */
public class CertificateField {
    
    public static final int X509 = 0x00;
        
    private int format;
    private CertificateBytes[] chain;
    private URIRecord uri;

    public CertificateField(int format, CertificateBytes[] chain) {
        this(format, chain, null);
    }
    
    public CertificateField(int format, URIRecord uri) {
        this(format, new CertificateBytes[0], uri);
    }
    
    public CertificateField(int format, CertificateBytes[] chain, URIRecord uri) {
        this.format = format;
        this.chain = chain;
        this.uri = uri;
        
        if(format >= 0x02) {
            throw new IllegalArgumentException("Invalid signature record due to use of RFU certificate format"); // TODO: Perhaps move this check to higher level logic
        }
        if(chain == null) {
            throw new NullPointerException("Certificate chain is null");
        }
    }
    
    private CertificateField() {
    }
    
    static CertificateField createEmpty() {
        return new CertificateField();
    }

    public CertificateBytes[] getChain() {
        return chain;
    }

    public int getFormat() {
        return format;
    }

    public URIRecord getUri() {
        return uri;
    }

    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final CertificateField other = (CertificateField) obj;
        if (this.format != other.format) {
            return false;
        }
        if (this.chain != other.chain && (this.chain == null || !Arrays.equals(this.chain, other.chain))) {
            return false;
        }
        if (this.uri != other.uri && (this.uri == null || !this.uri.equals(other.uri))) {
            return false;
        }
        return true;
    }

    public int hashCode() {
        int hash = 3;
        hash = 29 * hash + this.format;
        hash = 29 * hash + (this.chain != null ? Arrays.hashCode(this.chain) : 0);
        hash = 29 * hash + (this.uri != null ? this.uri.hashCode() : 0);
        return hash;
    }

    public String toString() {
        StringBuffer sb = new StringBuffer();
        sb.append("Cert(");
        if(getChain() != null) {
            sb.append("format:");
            sb.append(getFormat());
            sb.append(", num:");
            sb.append(getChain().length);
        }
        sb.append(")");
        return sb.toString();
    }
}
